// © 2009 Microsoft Corporation.  All rights reserved.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Tasks;
using Microsoft.InformationSecurity.RiskManagement.ISRMWeb.NotificationsService;
using Microsoft.Security.Application;
using Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Common;

namespace Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Tasks
{
    public partial class ManageNotificationContents : System.Web.UI.Page
    {
        List<NotificationContent> lstContents = new List<NotificationContent>();

        public void Page_Error(object sender, EventArgs e)
        {
            if (Server.GetLastError() is HttpException)
            {
                throw new HttpException(((HttpException)Server.GetLastError()).GetHttpCode(), Server.GetLastError().Message);
            }
            else
                throw new HttpException(500, "Unhandled Exception.");
        }


        protected void Page_Load(object sender, EventArgs e)
        {

            if (!this.Context.User.IsInRole(Utility.GetConfigurationValue("TaskAdmin")))
                throw new HttpException(403, "Requires Task Administrator Role");

            if (ViewState["NotificationContents"] == null)
            {
                lstContents = new List<NotificationContent>();
                NotificationsServiceClient notClient = new NotificationsServiceClient();
                lstContents.AddRange(notClient.GetNotificationContents());
                ViewState["NotificationContents"] = lstContents;
                notClient.Close();
            }
            else
            {
                lstContents = (List<NotificationContent>)ViewState["NotificationContents"];
            }
            if (!Page.IsPostBack)
            {
                this.DoDataBind();
                lblPageHeader.Text = "Manage Notification Contents";
            }
            
        }

        private void DoDataBind()
        {
            GridView1.DataSource = lstContents;
            GridView1.Columns[7].Visible = true;
            GridView1.DataBind();
            GridView1.Columns[7].Visible = false;
        }
        protected void GridView1_OnRowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {

                foreach (System.Web.UI.Control BaseControl in e.Row.Cells[1].Controls)
                {
                    if (BaseControl.GetType().BaseType == typeof(LinkButton))
                    {
                        LinkButton linkBtn = (LinkButton)BaseControl;
                        if (linkBtn.CommandName == "Delete")
                            if (int.Parse(e.Row.Cells[4].Text) > 0)
                                linkBtn.OnClientClick = "alert('" + Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "CONT_DEL_ERR",4) + "'); return false;";
                            else
                                linkBtn.OnClientClick = "return confirm('" + Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "CONT_DEL_CONFIRM",4) + "');";
                    }
                }
                

            }
        }

        protected void GridView1_OnRowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int contentID = int.Parse(GridView1.Rows[e.RowIndex].Cells[7].Text);
            if (contentID > 0)
            {
                NotificationContent updatedContent = null;
                foreach (NotificationContent c in lstContents)
                {
                    if (c.ID == contentID)
                    {
                        updatedContent = c;
                        break;
                    }
                }
                if (updatedContent != null)
                {
                    NotificationsServiceClient notClient = new NotificationsServiceClient();
                    try
                    {
                        notClient.DeleteNotificationContent(updatedContent.ID, ((CISF.Security.Principal.CISFIdentity)User.Identity).PersonId);
                        lstContents.Remove(updatedContent);
                        ViewState["NotificationContents"] = lstContents;
                        notClient.Close();
                    }
                    catch (System.ServiceModel.FaultException<System.ServiceModel.ExceptionDetail> fex)
                    {
                        if (fex.Detail.Type == typeof(ArgumentException).ToString() || fex.Detail.Type == typeof(ArgumentNullException).ToString())
                        {
                            Utility.ShowMessage(this.Master, fex.Message.ToString(), "Error", true);
                        }
                        else
                            Utility.ShowMessage(this.Master, Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "CONT_SAVE_UNKWNERR"), "Error", true);
                    }
                    catch
                    {
                        Utility.ShowMessage(this.Master, Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "CONT_SAVE_UNKWNERR"), "Error", true);
                    }
                }
            }
            DoDataBind();
        }

        protected void GridView1_OnRowEditing(object sender, GridViewEditEventArgs e)
        {
            
            int contentID = int.Parse(GridView1.Rows[e.NewEditIndex].Cells[7].Text);
            if (contentID > 0)
            {
                
                NotificationContent updatedContent = null;
                foreach (NotificationContent c in lstContents)
                {
                    if (c.ID == contentID)
                    {
                        updatedContent = c;
                        break;
                    }
                }
                if (updatedContent != null)
                {
                    
                    ViewState["IsEditing"] = true;
                    lblHeader.Text = "Edit Notification Content";
                    txtName.Text = updatedContent.Name;
                    
                    ViewState["EditingContentID"] = updatedContent.ID;
                    if (updatedContent.IsHtml == true)
                    {
                        htmlEditor.SelectedEditorTab = "HTML";
                        htmlEditor.Text = updatedContent.Body;
                    }
                    else
                    {
                        htmlEditor.SelectedEditorTab = "Text";
                        htmlEditor.textEditorDefault.Value = updatedContent.Body;
                    }
                    mpeContents.Show();
                }
            }

        }


        protected void GridView1_OnSorting(object sender, GridViewSortEventArgs e)
        {
            if (ViewState["GridSortDirection"] != null)
                if (ViewState["GridSortDirection"].ToString() == SortDirection.Ascending.ToString())
                    e.SortDirection = SortDirection.Descending;
                else
                    e.SortDirection = SortDirection.Ascending;

            lstContents.Sort(new NotificationContentComparer(e.SortDirection, e.SortExpression));

            ViewState["GridSortDirection"] = e.SortDirection;
            ViewState["GridSortExpression"] = e.SortExpression;
            this.DoDataBind();
        }

        public static string GetBodyType(bool isHtml) 
        {
            if (isHtml)
                return "HTML";
            else
                return "Text";
        }
        protected void btnAddNew_OnClick(object sender, EventArgs e)
        {
            ViewState["IsEditing"] = false;
            lblHeader.Text = "Create Notification Content";
            htmlEditor.SelectedEditorTab = "HTML";
            txtName.Text = "";
            htmlEditor.Text = "";
            htmlEditor.textEditorDefault.Value = "Text Version of HTML";
            mpeContents.Show();
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtName.Text) && !string.IsNullOrEmpty(htmlEditor.Text))
            {
                try
                {
                    NotificationContent content = null;
                    if ((bool)ViewState["IsEditing"] == true)
                    {
                        int id = (int)ViewState["EditingContentID"];
                        foreach (NotificationContent c in lstContents)
                        {
                            if (c.ID == id)
                            {
                                content = c;
                                break;
                            }
                        }
                    }
                    else 
                    {
                        content = new NotificationContent();
                    }
                    if (content != null)
                    {
                        content.Name = txtName.Text;
                        if (htmlEditor.SelectedEditorTab.ToLower() == "html")
                        {
                            content.IsHtml = true;
                        }
                        else
                        {
                            content.IsHtml = false;
                        }
                        content.Body = htmlEditor.Text;
                        content.LastUpdatedBy = Utility.GetUserFullName();
                        content.LastUpdatedDate = DateTime.Now;
                        content.PersonID = ((CISF.Security.Principal.CISFIdentity)User.Identity).PersonId;
                        NotificationsServiceClient objClient = new NotificationsServiceClient();
                        if ((bool)ViewState["IsEditing"] == true)
                        {
                            objClient.UpdateNotificationContent(content);
                        }
                        else
                        {
                            int contentID = objClient.AddNotificationContent(content);
                            content.ID = contentID;
                        }
                        if ((bool)ViewState["IsEditing"] == false)
                        {
                            lstContents.Add(content);
                        }
                        ViewState["NotificationContents"] = lstContents;
                        objClient.Close();
                        this.DoDataBind();
                        ScriptManager.RegisterStartupScript(this, typeof(Page), "closeModal", "hideModalPopup();", true);
                    }
                    else 
                    {
                        Utility.ShowMessage(this.Master, Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "CONT_DOESNOT_EXIST"), "Error", true);
                    }
                }
                catch (System.ServiceModel.FaultException<System.ServiceModel.ExceptionDetail> fex)
                {
                    if (fex.Detail.Type == typeof(ArgumentException).ToString() || fex.Detail.Type == typeof(ArgumentNullException).ToString())
                    {
                        Utility.ShowMessage(this.Master, fex.Message.ToString(), "Error", true);
                    }
                    else
                        Utility.ShowMessage(this.Master, Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "CONT_SAVE_UNKWNERR"), "Error", true);
                }
                catch
                {
                    Utility.ShowMessage(this.Master, Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "CONT_SAVE_UNKWNERR"), "Error", true);
                }
            }
            else
            {
                Utility.ShowMessage(this.Master, Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "CONT_NAME_REQ"),"Error",true);
            }
        }

       
        
    }

    class NotificationContentComparer : IComparer<NotificationContent>
    {
        SortDirection sortDir = SortDirection.Ascending;
        string sortExpr = "";
        public NotificationContentComparer(SortDirection sortDirection, string sortExpression)
        {
            sortDir = sortDirection;
            sortExpr = sortExpression;
        }

        public int Compare(NotificationContent x, NotificationContent y)
        {
            switch (sortExpr)
            {
                case "Name":
                    if (sortDir == SortDirection.Ascending)
                        return StringComparer.CurrentCultureIgnoreCase.Compare(x.Name, y.Name);
                    else
                        return StringComparer.CurrentCultureIgnoreCase.Compare(y.Name, x.Name);
                case "LastUpdatedBy":
                    if (sortDir == SortDirection.Ascending)
                        return StringComparer.CurrentCultureIgnoreCase.Compare(x.LastUpdatedBy, y.LastUpdatedBy);
                    else
                        return StringComparer.CurrentCultureIgnoreCase.Compare(y.LastUpdatedBy, x.LastUpdatedBy);
                case "LastUpdatedDate":
                    if (sortDir == SortDirection.Ascending)
                        return DateTime.Compare(x.LastUpdatedDate, y.LastUpdatedDate);
                    else
                        return DateTime.Compare(y.LastUpdatedDate, x.LastUpdatedDate);
                case "NotificationsCount":
                    if (sortDir == SortDirection.Ascending)
                        if (x.NotificationsCount > y.NotificationsCount)
                            return 1;
                        else if (x.NotificationsCount < y.NotificationsCount)
                            return -1;
                        else
                            return 0;
                    else
                        if (y.NotificationsCount > x.NotificationsCount)
                            return 1;
                        else if (y.NotificationsCount < x.NotificationsCount)
                            return -1;
                        else
                            return 0;
                case "IsHtml":
                    if (sortDir == SortDirection.Ascending)
                        return x.IsHtml.CompareTo(y.IsHtml);
                    else
                        return y.IsHtml.CompareTo(x.IsHtml);
            }
            return 0;
        }

        

    }
}
